#!/data/data/com.termux/files/usr/bin/bash
# =========================================================================
# Violet SillyTavern酒馆多功能面板 v3.22
# 作者: 紫罗兰
# =========================================================================

# ==== 基础配色定义 ====
RED='\033[1;31m'        # 红色
GREEN='\033[1;32m'      # 绿色
YELLOW='\033[1;33m'     # 黄色
BLUE='\033[1;34m'       # 蓝色
CYAN='\033[1;36m'       # 青色
WHITE='\033[1;37m'      # 白色
NC='\033[0m'            # 重置颜色

# ==== 脚本信息 ====
SCRIPT_VERSION="3.22"
AUTHOR="紫罗兰"
UPDATE_DATE="2025-11-08"
MAIN_GROUP="一群1037161927(群满)二群1063330958"
NEW_GROUP="940036726"

# ==== 路径定义 ====
SILLYTAVERN_PATH="$HOME/SillyTavern"
BACKUP_PATH="$HOME/sillytavern_backup"
UBUNTU_ROOT="/data/data/com.termux/files/usr/var/lib/proot-distro/installed-rootfs/ubuntu"
TERMUX_SOURCES_LIST="/data/data/com.termux/files/usr/etc/apt/sources.list"

# ==== 新脚本的配置 ====
GH1=("https://hub.gitmirror.com/https://github.com" "https://github.tbedu.top/https://github.com" "https://ghproxy.net/https://github.com")
GH2=("https://github.tbedu.top/https://github.com" "https://hub.gitmirror.com/https://github.com" "https://ghproxy.net/https://github.com")
NPM="https://registry.npmmirror.com"
PREFIX="${PREFIX:-/data/data/com.termux/files/usr}"
SILLY="$HOME/SillyTavern"
UBUNTU_ROOT="$PREFIX/var/lib/proot-distro/installed-rootfs/ubuntu"

# =========================================================================
# 提示函数
# =========================================================================
say_hello() {
    echo -e "${BLUE}欢迎使用紫罗兰管理面板${NC}"
}

say_working() {
    echo -e "${CYAN}正在为您$1，请稍等片刻${NC}"
}

say_success() {
    echo -e "${GREEN}$1成功完成${NC}"
}

say_warning() {
    echo -e "${YELLOW}温馨提示：$1${NC}"
}

say_error() {
    echo -e "${RED}抱歉，出现了问题：$1${NC}"
    echo -e "${RED}建议解决方案：${NC}"
    echo -e "${WHITE}1. 更换部署方式${NC}"
    echo -e "${WHITE}2. 加群询问：${MAIN_GROUP}${NC}"
    echo -e "${WHITE}3. 更新更换termux${NC}"
}

say_info() {
    echo -e "${BLUE}$1${NC}"
}

# ==== 新脚本的工具函数 ====
red() { echo -e "\033[31m$1\033[0m"; }
green() { echo -e "\033[32m$1\033[0m"; }
yellow() { echo -e "\033[33m$1\033[0m"; }
blue() { echo -e "\033[34m$1\033[0m"; }
cyan() { echo -e "\033[36m$1\033[0m"; }

err() { red "❌ $1"; exit 1; }
ok() { green "✅ $1"; }
info() { cyan "ℹ️  $1"; }
warn() { yellow "⚠️  $1"; }
step() { blue "🔹 $1"; }

log() {
    echo "[$(date '+%H:%M:%S')] $1"
}

run_cmd() {
    local cmd="$1"
    local desc="$2"
    
    step "$desc"
    log "执行: $cmd"
    
    if eval "$cmd" 2>&1; then
        ok "$desc 完成"
        return 0
    else
        err "$desc 失败"
        return 1
    fi
}

# =========================================================================
# 面板界面
# =========================================================================
print_banner() {
    clear
    echo ""
    echo -e "${CYAN} __      _______ ____  _      ______ _______ ${NC}"
    echo -e "${CYAN} \\ \\    / /_   _/ __ \\| |    |  ____|__   __|${NC}"
    echo -e "${CYAN}  \\ \\  / /  | || |  | | |    | |__     | |   ${NC}"
    echo -e "${CYAN}   \\ \\/ /   | || |  | | |    |  __|    | |   ${NC}"
    echo -e "${CYAN}    \\  /   _| || |__| | |____| |____   | |   ${NC}"
    echo -e "${CYAN}     \\/   |_____\\____/|______|______|  |_|   ${NC}"
    echo ""
    echo -e "${BLUE}        SillyTavern酒馆多功能面板        ${NC}"
    echo ""
    echo -e "${WHITE}作者：${AUTHOR}    脚本版本：v${SCRIPT_VERSION}    更新日期：${UPDATE_DATE}${NC}"
    echo ""
    echo -e "${YELLOW}任何报错可加群获得最新脚本${NC}"
    echo -e "${WHITE}大群交流群，api购买Q群：${MAIN_GROUP}${NC}"
    echo -e "${WHITE}萌新互助群，免费gemini全女公益站：${NEW_GROUP}${NC}"
    echo -e "${RED}请勿使用作者为 呆呆鸟 的盗版脚本！！！${NC}"
    echo ""
}

print_main_menu() {
    echo -e "${GREEN}主要功能：${NC}"
    echo ""
    echo -e "  ${BLUE}1.${NC} 一键部署 SillyTavern 酒馆"
    echo -e "  ${BLUE}2.${NC} 启动 SillyTavern 酒馆"
    echo -e "  ${BLUE}3.${NC} 更新 SillyTavern 酒馆"
    echo -e "  ${BLUE}4.${NC} 安装酒馆插件"
    echo ""
    echo -e "${GREEN}更多服务：${NC}"
    echo ""
    echo -e "  ${BLUE}5.${NC} 关于交流群"
    echo -e "  ${BLUE}6.${NC} 获取免费API"
    echo ""
    echo ""
    echo -e "  ${BLUE}0.${NC} 退出面板"
    echo ""
}

# =========================================================================
# 功能1：一键部署 SillyTavern (使用新脚本的完整部署功能)
# =========================================================================
deploy_sillytavern() {
    print_banner
    say_hello
    echo ""

    if [ -d "$SILLYTAVERN_PATH" ]; then
        say_warning "检测到已安装 SillyTavern"
        echo ""
        read -p "$(echo -e ${YELLOW}是否重新部署？[y/N]: ${NC})" redeploy
        if [[ ! "$redeploy" =~ ^[Yy]$ ]]; then
            return 0
        fi
        rm -rf "$SILLYTAVERN_PATH"
    fi

    # 显示部署选项
    echo -e "${CYAN}请选择部署方式：${NC}"
    echo ""
    echo -e "  ${BLUE}1.${NC} Termux 主选源（免翻墙，推荐）"
    echo -e "  ${BLUE}2.${NC} Termux 备选源（免翻墙，备用）"
    echo -e "  ${BLUE}3.${NC} Ubuntu 容器方案（老机型/特殊CPU）"
    echo -e "  ${BLUE}4.${NC} VPN 直连方案（有VPN用户使用）"
    echo -e "${YELLOW}请确保termux的版本足够新且一定不是从google play谷歌商店下载的版本${NC}"
    echo -e "${YELLOW}请从git官方渠道下载termux或进群获取安装包 ${NC}"
    echo -e "${YELLOW}github链接为：https://github.com/termux/termux-app/releases${NC}"

    echo ""

    while true; do
        read -p "$(echo -e ${YELLOW}请选择部署方式 [1-4]: ${NC})" deploy_choice
        case $deploy_choice in
            1)
                deploy_with_option 1
                break
                ;;
            2)
                deploy_with_option 2
                break
                ;;
            3)
                deploy_with_option 3
                break
                ;;
            4)
                deploy_with_option 4
                break
                ;;
            *)
                say_error "无效选择，请重新输入"
                ;;
        esac
    done
}

deploy_with_option() {
    local option=$1
    case $option in
        1)
            GH=("${GH1[@]}")
            deploy_termux
            ;;
        2)
            GH=("${GH2[@]}")
            deploy_termux
            ;;
        3)
            deploy_ubuntu
            ;;
        4)
            GH=("https://github.com")
            NPM="https://registry.npmjs.org"
            deploy_termux
            ;;
    esac
    
    make_menu
    say_success "部署完成！"
    
    case $option in
        1|2|4)
            say_info "重启 Termux 即可看到菜单，或运行: bash ~/st-menu.sh"
            ;;
        3)
            say_info "运行以下命令启动Ubuntu中的SillyTavern:"
            echo -e "${WHITE}bash ~/start-ubuntu-st.sh${NC}"
            ;;
    esac
    
    echo ""
    read -p "$(echo -e ${YELLOW}按回车键返回主菜单...${NC})"
}

# ==== 新脚本的部署函数 ====
deploy_termux() {
    info "=== 开始Termux部署 ==="
    
    run_cmd "termux-setup-storage" "获取存储权限"
    
    run_cmd "ln -sf /data/data/com.termux/files/usr/etc/termux/mirrors/chinese_mainland/mirrors.tuna.tsinghua.edu.cn /data/data/com.termux/files/usr/etc/termux/chosen_mirrors" "配置Termux清华源"
    
    run_cmd "pkg update -y -o Dpkg::Options::=\"--force-confnew\"" "更新包列表"
    
    run_cmd "pkg install -y git curl zip unzip" "安装基础工具"
    
    run_cmd "pkg install -y nodejs-lts || pkg install -y nodejs" "安装Node.js"
    
    run_cmd "npm config set registry \"$NPM\"" "配置NPM镜像源"
    
    info "=== 获取SillyTavern ==="
    if [ -d "$SILLY/.git" ]; then
        step "更新现有仓库"
        cd "$SILLY"
        if git pull; then
            ok "更新成功"
        else
            warn "更新失败，重新克隆"
            rm -rf "$SILLY"
        fi
    fi
    
    if [ ! -d "$SILLY/.git" ]; then
        step "克隆SillyTavern仓库"
        local cloned=0
        for u in "${GH[@]}"; do
            log "尝试: $u"
            if timeout 60 git clone --depth=1 --single-branch -b release --progress "$u/SillyTavern/SillyTavern" "$SILLY" 2>&1; then
                ok "克隆成功: $(echo $u | cut -d'/' -f3)"
                cloned=1
                break
            else
                warn "克隆失败: $(echo $u | cut -d'/' -f3)"
                rm -rf "$SILLY" 2>/dev/null
            fi
        done
        
        if [ $cloned -eq 0 ]; then
            err "所有Git源都失败了"
        fi
    fi
    
    info "=== 安装依赖 ==="
    cd "$SILLY"
    run_cmd "rm -rf node_modules package-lock.json" "清理旧依赖"
    run_cmd "npm install --no-audit --no-fund --loglevel=info --omit=dev" "安装Node.js依赖"
}

deploy_ubuntu() {
    info "=== 开始Ubuntu容器部署 ==="
    
    run_cmd "termux-setup-storage" "获取存储权限"
    
    run_cmd "pkg install -y proot-distro" "安装proot-distro"
    
    if [ ! -d "$UBUNTU_ROOT" ]; then
        step "安装Ubuntu系统"
        log "这可能需要较长时间，请耐心等待..."
        export PROOT_DISTRO_MIRROR="https://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/"
        if DEBIAN_FRONTEND=noninteractive proot-distro install ubuntu; then
            ok "Ubuntu系统安装完成"
        else
            err "Ubuntu系统安装失败"
        fi
    else
        info "Ubuntu系统已存在"
    fi
    
    step "创建Ubuntu内部部署脚本"
    cat > "$HOME/ubuntu-deploy.sh" << 'EOF'
#!/bin/bash
set -e
echo "=== 在Ubuntu中部署SillyTavern ==="

echo "步骤1: 更新系统包..."
apt update && apt upgrade -y

echo "步骤2: 安装基础工具..."
apt install -y curl wget git unzip tar

echo "步骤3: 下载Node.js..."
cd /root
if [ ! -f "node-v22.16.0-linux-arm64.tar.xz" ]; then
    echo "下载Node.js v22.16.0..."
    wget https://nodejs.org/dist/v22.16.0/node-v22.16.0-linux-arm64.tar.xz
    echo "解压Node.js..."
    tar -xf node-v22.16.0-linux-arm64.tar.xz
    echo "配置环境变量..."
    echo 'export PATH=$PATH:/root/node-v22.16.0-linux-arm64/bin' >> /etc/profile
fi

echo "步骤4: 设置Node.js环境..."
export PATH=$PATH:/root/node-v22.16.0-linux-arm64/bin
npm config set registry https://registry.npmmirror.com

echo "步骤5: 下载SillyTavern..."
if [ -d "/root/SillyTavern" ]; then
    echo "更新现有仓库..."
    cd /root/SillyTavern
    git pull
else
    echo "克隆新仓库..."
    git clone --depth 1 -b release https://hub.gitmirror.com/https://github.com/SillyTavern/SillyTavern /root/SillyTavern
    cd /root/SillyTavern
fi

echo "步骤6: 安装依赖..."
npm install --no-audit --no-fund --loglevel=info --omit=dev

echo "=== Ubuntu部署完成 ==="
EOF

    run_cmd "chmod +x \"$HOME/ubuntu-deploy.sh\"" "设置执行权限"
    
    step "在Ubuntu中执行部署"
    log "进入Ubuntu环境..."
    if proot-distro login ubuntu -- "/root/ubuntu-deploy.sh"; then
        ok "Ubuntu内部部署完成"
    else
        err "Ubuntu内部部署失败"
    fi
    
    step "创建启动脚本"
    cat > "$HOME/start-ubuntu-st.sh" << 'EOF'
#!/bin/bash
echo "启动Ubuntu中的SillyTavern..."
echo "访问地址: http://localhost:8000"
echo "停止服务: 按 Ctrl+C"
proot-distro login ubuntu -- /bin/bash -c 'export PATH=$PATH:/root/node-v22.16.0-linux-arm64/bin && cd /root/SillyTavern && node server.js'
EOF

    run_cmd "chmod +x \"$HOME/start-ubuntu-st.sh\"" "设置执行权限"
}

make_menu() {
    step "创建管理菜单"
    cat > "$HOME/st-menu.sh" << 'EOF'
#!/bin/bash
while true; do
    clear
    echo "======== SillyTavern 快捷菜单 ========"
    echo "1) 启动 SillyTavern"
    echo "2) 退出"
    read -p "请选择(1/2): " c
    case $c in
        1) 
            if [ -d "$HOME/SillyTavern" ]; then
                cd "$HOME/SillyTavern"
                echo "启动中... 访问 http://localhost:8000"
                node server.js
            else
                echo "SillyTavern未安装"
                read -p "按回车键继续..."
            fi
            ;;
        2) exit 0 ;;
        *) echo "请输入 1 或 2";;
    esac
done
EOF

    run_cmd "chmod +x \"$HOME/st-menu.sh\"" "设置执行权限"
    
    step "配置自动启动"
    if ! grep -q "st-menu.sh" "$HOME/.bashrc"; then
        echo 'bash $HOME/st-menu.sh' >> "$HOME/.bashrc"
        ok "自动启动配置完成"
    else
        info "自动启动已配置"
    fi
}

# =========================================================================
# 功能2：启动 SillyTavern
# =========================================================================
start_sillytavern() {
    print_banner
    say_hello
    echo ""

    if [ ! -d "$SILLYTAVERN_PATH" ]; then
        # 检查Ubuntu部署
        if [ -d "$UBUNTU_ROOT/root/SillyTavern" ]; then
            say_info "检测到Ubuntu部署，正在启动"
            echo -e "${WHITE}正在执行: bash ~/start-ubuntu-st.sh${NC}"
            bash ~/start-ubuntu-st.sh
        else
            say_error "还没有安装 SillyTavern"
            say_info "请先使用部署功能安装 SillyTavern"
            echo ""
            read -p "$(echo -e ${YELLOW}按回车键返回主菜单...${NC})"
        fi
        return 1
    fi

    say_working "启动 SillyTavern"
    echo ""

    cd "$SILLYTAVERN_PATH" || {
        echo -e "${RED}无法进入 SillyTavern 目录，完整错误信息：${NC}"
        ls -la "$HOME" 2>&1
        say_error "无法进入 SillyTavern 目录"
        return 1
    }

    say_success "SillyTavern 即将启动"
    say_info "访问地址：http://localhost:8000"
    say_info "停止服务：按 Ctrl+C"
    echo ""
    echo -e "${CYAN}尽情享受酒馆时光吧${NC}"
    echo ""

    # 启动服务
    echo -e "${WHITE}正在执行: node server.js${NC}"
    node server.js
}

# =========================================================================
# 功能3：更新 SillyTavern
# =========================================================================
update_sillytavern() {
    print_banner
    say_working "更新 SillyTavern"
    echo ""

    local st_path=""
    local is_ubuntu=false

    if [ -d "$SILLYTAVERN_PATH" ]; then
        st_path="$SILLYTAVERN_PATH"
    elif [ -d "$UBUNTU_ROOT/root/SillyTavern" ]; then
        st_path="$UBUNTU_ROOT/root/SillyTavern"
        is_ubuntu=true
    else
        say_error "还没有安装 SillyTavern，无法更新"
        echo ""
        read -p "$(echo -e ${YELLOW}按回车键返回主菜单...${NC})"
        return 1
    fi

    # 备份当前版本
    say_working "备份当前配置"
    if [ -d "$BACKUP_PATH" ]; then
        rm -rf "$BACKUP_PATH"
    fi

    mkdir -p "$BACKUP_PATH"
    if [ -d "$st_path/data" ]; then
        cp -r "$st_path/data" "$BACKUP_PATH/"
        say_success "配置文件备份"
    fi

    if [ -d "$st_path/public" ]; then
        cp -r "$st_path/public" "$BACKUP_PATH/"
        say_success "公共文件备份"
    fi

    cd "$st_path" || return 1

    # 拉取最新代码
    say_working "拉取最新版本"
    echo -e "${WHITE}正在执行: git pull origin release${NC}"
    if git pull origin release; then
        say_success "代码更新"
    else
        echo -e "${RED}代码拉取失败，完整错误信息：${NC}"
        git pull origin release 2>&1
        say_error "代码拉取失败，尝试重新克隆"

        local parent_dir=$(dirname "$st_path")
        cd "$parent_dir" || return 1
        rm -rf "SillyTavern_new"

        echo -e "${WHITE}正在执行: git clone https://github.com/SillyTavern/SillyTavern.git SillyTavern_new${NC}"
        if git clone https://github.com/SillyTavern/SillyTavern.git SillyTavern_new; then
            rm -rf "$st_path"
            mv "SillyTavern_new" "$st_path"
            say_success "重新安装完成"
        else
            echo -e "${RED}重新克隆失败，完整错误信息：${NC}"
            git clone https://github.com/SillyTavern/SillyTavern.git SillyTavern_new 2>&1
            say_error "更新失败，请检查网络连接"
            return 1
        fi
    fi

    # 恢复备份的配置
    cd "$st_path" || return 1
    if [ -d "$BACKUP_PATH/data" ]; then
        rm -rf "data"
        cp -r "$BACKUP_PATH/data" "./"
        say_success "配置文件恢复"
    fi

    if [ -d "$BACKUP_PATH/public" ]; then
        cp -r "$BACKUP_PATH/public"/* "public/"
        say_success "公共文件恢复"
    fi

    # 更新依赖
    say_working "更新依赖包"
    export NODE_ENV=production

    if [ "$is_ubuntu" = true ]; then
        echo -e "${WHITE}正在执行: Ubuntu环境下npm install${NC}"
        if ! proot-distro login ubuntu -- bash -c "cd /root/SillyTavern && export PATH=\$PATH:/root/node-v22.16.0-linux-arm64/bin && npm install --no-audit --no-fund --loglevel=error --omit=dev"; then
            echo -e "${RED}Ubuntu环境下依赖更新失败，完整错误信息：${NC}"
            proot-distro login ubuntu -- bash -c "cd /root/SillyTavern && export PATH=\$PATH:/root/node-v22.16.0-linux-arm64/bin && npm install --no-audit --no-fund --omit=dev" 2>&1
            say_error "依赖更新失败"
            return 1
        fi
    else
        echo -e "${WHITE}正在执行: npm install --no-audit --no-fund --loglevel=error --omit=dev${NC}"
        if ! npm install --no-audit --no-fund --loglevel=error --omit=dev; then
            echo -e "${RED}依赖更新失败，完整错误信息：${NC}"
            npm install --no-audit --no-fund --omit=dev 2>&1
            say_error "依赖更新失败"
            return 1
        fi
    fi

    say_success "依赖更新完成"

    echo ""
    say_success "SillyTavern 更新完成"
    say_info "您可以重新启动酒馆来体验新功能了"
    echo ""
    read -p "$(echo -e ${YELLOW}按回车键返回主菜单...${NC})"
}

# =========================================================================
# 功能4：安装酒馆插件
# =========================================================================
install_plugins() {
    print_banner
    say_working "准备安装插件"
    echo ""

    local st_path=""
    local is_ubuntu=false

    if [ -d "$SILLYTAVERN_PATH" ]; then
        st_path="$SILLYTAVERN_PATH"
    elif [ -d "$UBUNTU_ROOT/root/SillyTavern" ]; then
        st_path="$UBUNTU_ROOT/root/SillyTavern"
        is_ubuntu=true
    else
        say_error "还没有安装 SillyTavern，请先安装"
        echo ""
        read -p "$(echo -e ${YELLOW}按回车键返回主菜单...${NC})"
        return 1
    fi

    echo -e "${GREEN}可用插件：${NC}"
    echo ""
    echo -e "  ${BLUE}1.${NC} 酒馆助手"
    echo -e "${WHITE}     目前效果最强泛用性最强的扩展插件，美化扩展必须安装，手机界面必须安装${NC}"
    echo ""
    echo -e "  ${BLUE}2.${NC} 聊天记录管理器"
    echo -e "${WHITE}     上限极高的扩展，配置向量化重排序模型轻松玩上万楼不失忆，有一定上手难度且需要特殊模型，但依旧建议安装，加群获得最详细教程以及相关所需模型。${NC}"
    echo ""
    echo -e "  ${BLUE}0.${NC} 返回主菜单"
    echo ""

    read -p "$(echo -e ${YELLOW}请选择要安装的插件 [0-2]: ${NC})" plugin_choice

    case $plugin_choice in
        1)
            install_tavern_helper "$st_path" "$is_ubuntu"
            ;;
        2)
            install_chat_manager "$st_path" "$is_ubuntu"
            ;;
        0)
            return 0
            ;;
        *)
            say_error "无效的选择"
            sleep 2
            install_plugins
            ;;
    esac
}

# 安装酒馆助手插件
install_tavern_helper() {
    local st_path="$1"
    local is_ubuntu="$2"

    say_working "安装酒馆助手插件"

    if [ "$is_ubuntu" = true ]; then
        # Ubuntu环境下的安装
        echo -e "${WHITE}正在执行: Ubuntu环境下克隆酒馆助手插件${NC}"
        if ! proot-distro login ubuntu -- bash -c "
            mkdir -p /root/SillyTavern/public/scripts/extensions/third-party
            cd /root/SillyTavern/public/scripts/extensions/third-party
            if [ -d 'JS-Slash-Runner' ]; then
                rm -rf JS-Slash-Runner
            fi
            if git clone https://github.com/N0VI028/JS-Slash-Runner.git; then
                echo '酒馆助手插件安装成功'
            else
                echo '酒馆助手插件安装失败'
                exit 1
            fi
        "; then
            echo -e "${RED}Ubuntu环境下酒馆助手插件安装失败，完整错误信息：${NC}"
            proot-distro login ubuntu -- bash -c "
                cd /root/SillyTavern/public/scripts/extensions/third-party
                git clone https://github.com/N0VI028/JS-Slash-Runner.git
            " 2>&1
            say_error "酒馆助手插件安装失败"
        else
            say_success "酒馆助手插件安装完成"
            say_info "启动酒馆后可在扩展管理中启用"
        fi
    else
        # Termux环境下的安装
        local extensions_dir="$st_path/public/scripts/extensions/third-party"
        mkdir -p "$extensions_dir"
        cd "$extensions_dir" || return 1

        if [ -d "JS-Slash-Runner" ]; then
            rm -rf "JS-Slash-Runner"
        fi

        echo -e "${WHITE}正在执行: git clone https://github.com/N0VI028/JS-Slash-Runner.git${NC}"
        if git clone https://github.com/N0VI028/JS-Slash-Runner.git; then
            say_success "酒馆助手插件安装完成"
            say_info "启动酒馆后可在扩展管理中启用"
        else
            echo -e "${RED}酒馆助手插件安装失败，完整错误信息：${NC}"
            git clone https://github.com/N0VI028/JS-Slash-Runner.git 2>&1
            say_error "酒馆助手插件安装失败"
        fi
    fi

    echo ""
    read -p "$(echo -e ${YELLOW}按回车键返回主菜单...${NC})"
}

# 安装聊天记录管理器插件
install_chat_manager() {
    local st_path="$1"
    local is_ubuntu="$2"

    say_working "安装聊天记录管理器插件"

    if [ "$is_ubuntu" = true ]; then
        # Ubuntu环境下的安装
        echo -e "${WHITE}正在执行: Ubuntu环境下克隆聊天记录管理器插件${NC}"
        if ! proot-distro login ubuntu -- bash -c "
            mkdir -p /root/SillyTavern/public/scripts/extensions/third-party
            cd /root/SillyTavern/public/scripts/extensions/third-party
            if [ -d 'vectors-enhanced' ]; then
                rm -rf vectors-enhanced
            fi
            if git clone https://github.com/RaphllA/vectors-enhanced.git; then
                echo '聊天记录管理器插件安装成功'
            else
                echo '聊天记录管理器插件安装失败'
                exit 1
            fi
        "; then
            echo -e "${RED}Ubuntu环境下聊天记录管理器插件安装失败，完整错误信息：${NC}"
            proot-distro login ubuntu -- bash -c "
                cd /root/SillyTavern/public/scripts/extensions/third-party
                git clone https://github.com/RaphllA/vectors-enhanced.git
            " 2>&1
            say_error "聊天记录管理器插件安装失败"
        else
            say_success "聊天记录管理器插件安装完成"
            say_info "此插件可以增强聊天记录的管理功能"
        fi
    else
        # Termux环境下的安装
        local extensions_dir="$st_path/public/scripts/extensions/third-party"
        mkdir -p "$extensions_dir"
        cd "$extensions_dir" || return 1

        if [ -d "vectors-enhanced" ]; then
            rm -rf "vectors-enhanced"
        fi

        echo -e "${WHITE}正在执行: git clone https://github.com/RaphllA/vectors-enhanced.git${NC}"
        if git clone https://github.com/RaphllA/vectors-enhanced.git; then
            say_success "聊天记录管理器插件安装完成"
            say_info "此插件可以增强聊天记录的管理功能"
        else
            echo -e "${RED}聊天记录管理器插件安装失败，完整错误信息：${NC}"
            git clone https://github.com/RaphllA/vectors-enhanced.git 2>&1
            say_error "聊天记录管理器插件安装失败"
        fi
    fi

    echo ""
    read -p "$(echo -e ${YELLOW}按回车键返回主菜单...${NC})"
}

# =========================================================================
# 功能5-6：信息展示功能
# =========================================================================
show_contact_info() {
    print_banner
    echo -e "${GREEN}关于交流群${NC}"
    echo ""
    echo -e "${BLUE}群吉祥物星星:${NC}"
    echo -e "${WHITE}欢迎uu们使用该脚本${NC}"
    echo -e "${WHITE}如果你是一位酒馆爱好者^-^${NC}"
    echo -e "${WHITE}我相信你会喜欢这里：${MAIN_GROUP}${NC}"
    echo ""
    echo -e "${WHITE}这里有——${NC}"
    echo -e "${YELLOW}★优质api${NC}"
    echo -e "${WHITE}满血克劳德${NC}"
    echo -e "${WHITE}官转gemini${NC}"
    echo -e "${WHITE}超低价的deepseek${NC}"
    echo -e "${WHITE}……${NC}"
    echo -e "${WHITE}这里还有——${NC}"
    echo -e "${YELLOW}★详细教程${NC}"
    echo -e "${YELLOW}★报错大全和解决办法${NC}"
    echo -e "${YELLOW}★角色卡分享/定制${NC}"
    echo -e "${YELLOW}★安卓/ios/pc酒馆任何问题${NC}"
    echo -e "${WHITE}……${NC}"
    echo -e "${WHITE}你是否苦恼于${NC}"
    echo -e "${RED}爆红/空回/截断/道歉/重复/失忆/掉状态栏？${NC}"
    echo -e "${RED}缺少好用的加速器/魔法/梯子？${NC}"
    echo -e "${RED}预设/正则/插件/角色卡？${NC}"
    echo ""
    echo -e "${CYAN}立马添加${MAIN_GROUP}解决问题吧！${NC}"
    echo ""
    read -p "$(echo -e ${YELLOW}按回车键返回主菜单...${NC})"
}

show_free_api() {
    print_banner
    echo -e "${GREEN}获取免费API${NC}"
    echo -e "11.7日最新免费三千次api密钥sk-mSILWpoZhx2CfYnt9VnJg89MeywBulrzn6uxpEb729HDKf06，URL进群获得"
    echo -e "${BLUE}0基础新人过渡解答群：${NEW_GROUP}${NC}"
    echo -e "${WHITE}同时也是全女公益站的审核群，内含最全酒馆相关教程，活跃大佬很多，新人互相帮助解决报错。${NC}"
    echo ""
    echo -e "${WHITE}全女公益站需邀请制经过审核可加入，每日签到即可免费获得大量调用次数，无升级，无套餐，无限速，不可能在公益站内花费一分钱。${NC}"
    echo ""
    read -p "$(echo -e ${YELLOW}按回车键返回主菜单...${NC})"
}

# =========================================================================
# 主菜单循环
# =========================================================================
main_menu() {
    while true; do
        print_banner
        print_main_menu

        read -p "$(echo -e ${YELLOW}请选择功能 [0-6]: ${NC})" choice

        case $choice in
            1)
                deploy_sillytavern
                ;;
            2)
                start_sillytavern
                ;;
            3)
                update_sillytavern
                ;;
            4)
                install_plugins
                ;;
            5)
                show_contact_info
                ;;
            6)
                show_free_api
                ;;
            0)
                print_banner
                say_info "感谢使用 紫罗兰 管理面板"
                echo -e "${BLUE}下次见，祝您使用愉快${NC}"
                echo ""
                exit 0
                ;;
            *)
                say_error "选择无效，请输入0-6之间的数字"
                sleep 2
                ;;
        esac
    done
}

# =========================================================================
# 自启动配置
# =========================================================================
setup_autostart() {
    local bashrc_file="$HOME/.bashrc"
    local script_path="$HOME/violet.sh"

    # 检查是否已配置自启动
    if ! grep -q "violet.sh" "$bashrc_file" 2>/dev/null; then
        echo "" >> "$bashrc_file"
        echo "# Violet SillyTavern 管理面板自启动" >> "$bashrc_file"
        echo "if [ -f \"$script_path\" ]; then" >> "$bashrc_file"
        echo "    bash \"$script_path\"" >> "$bashrc_file"
        echo "fi" >> "$bashrc_file"

        say_success "自启动配置完成"
        say_info "下次打开Termux将直接显示管理面板"
    fi
}

# =========================================================================
# 脚本入口点
# =========================================================================
# 将脚本复制到用户目录
if [ "$0" != "$HOME/violet.sh" ] && [ ! -f "$HOME/violet.sh" ]; then
    cp "$0" "$HOME/violet.sh"
    chmod +x "$HOME/violet.sh"
fi

# 检查是否是首次运行，如果是则配置自启动
if [ ! -f "$HOME/.violet_configured" ]; then
    setup_autostart
    touch "$HOME/.violet_configured"
fi

# 启动主菜单
main_menu